package com.doublefish.doublefishrobot.ui.home.s5;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;

import com.doublefish.doublefishrobot.R;
import com.doublefish.doublefishrobot.base.BaseActivity;
import com.doublefish.doublefishrobot.ui.home.bean.ModeSettingBean;
import com.doublefish.doublefishrobot.ui.home.path.DFPingPongTableView;
import com.doublefish.doublefishrobot.ui.home.widget.CustomNameDialog;
import com.doublefish.doublefishrobot.ui.home.widget.ModeSettingItemValuePopView;
import com.doublefish.doublefishrobot.ui.home.widget.S5ModeSettingItemContentView;
import com.doublefish.doublefishrobot.ui.home.widget.SafeDialog;
import com.doublefish.doublefishrobot.utils.AppCacheUtil;
import com.doublefish.doublefishrobot.utils.MessageEvent;
import com.doublefish.doublefishrobot.utils.ble.bean.ModeConstant;
import com.doublefish.doublefishrobot.utils.db.DataBaseApi;
import com.doublefish.doublefishrobot.utils.socket.DFS5ProtocolMaker;
import com.doublefish.doublefishrobot.widget.CommonDialog;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 作者:dugaofeng on 2024/12/30 10:34
 */
public class S5ModeNormalActivity extends BaseActivity {

    @BindView(R.id.tv_title)
    TextView titleTV;

    @BindView(R.id.pingpong_view)
    DFPingPongTableView pingPongTableView;

    @BindView(R.id.mode_normal_content)
    S5ModeSettingItemContentView normalContentView;

    private ModeSettingBean settingBean;
    private ModeSettingBean.ModeSettingStepBean stepBean;
    //循环配置
    private ModeSettingBean.ModeSettingLoopBean loopBean = ModeSettingBean.ModeSettingLoopBean.defaultLoop(ModeConstant.ProtocolTypeS5);


    @Override
    protected int getLayoutId() {
        return R.layout.activity_mode_normal_s5;
    }

    @Override
    protected void initView() {
        titleTV.setText(R.string.basic_mode);
    }

    @Override
    protected void initData() {
        //先写死  便于便于测试
        ModeSettingBean settingBean = new ModeSettingBean();
        settingBean.setProtocolType(ModeConstant.ProtocolTypeS5);
        settingBean.setName(getString(R.string.basic_mode));
        settingBean.setScript("0,0,3,3,6#");
        this.settingBean = settingBean;
        this.stepBean = settingBean.getSteps().get(0);
        reloadData();
    }

    @Override
    protected void initListener() {
        normalContentView.setOnModeSettingItemListner(new S5ModeSettingItemContentView.OnModeSettingItemListner() {
            @Override
            public void onModeSettingItemValueClick(ModeSettingBean.ModeSettingStepBean stepBean, ModeSettingBean.ModeSettingItemBean itemBean, ModeSettingBean.ModeSettingItemTag itemTag) {
                showItemValuePopView(stepBean ,itemBean, itemTag);
            }
        });
    }

    @OnClick(R.id.ll_back)
    public void onBackClick() {
        finish();
    }

    @OnClick({R.id.tv_save, R.id.tv_train})
    public void onBtnClick(View view) {
        switch (view.getId()) {
            case R.id.tv_save: {
                saveBallBtnClick();
            }
            break;
            case R.id.tv_train: {
                trainBtnClick();
            }
            break;
            default:
                break;
        }
    }

    private void reloadData() {
        normalContentView.setSettingStepBean(this.stepBean);
        pingPongTableView.setS5StepBean(stepBean);
    }

    private void saveBallBtnClick() {
        showTextFiledAlert(null);
    }

    private void trainBtnClick() {
        if (SafeDialog.shouldShowSafeDialog()) {
            boolean isHigSpeed = false;
            if (stepBean.getSpeedItemBean().getCurrentValue() > SafeDialog.S5_TIPS_MAX_SPEED) {
                isHigSpeed = true;
            }

            if (isHigSpeed) {
                new SafeDialog(this, new SafeDialog.OnDialogListner() {
                    @Override
                    public void onComfirmBtnClick() {
                        prepareTrain();
                    }

                    @Override
                    public void onCancelBtnClick() {

                    }
                }).show();
            } else {
                prepareTrain();
            }
        } else {
            prepareTrain();
        }
    }

    //准备训练 选择训练时间/次数
    private void prepareTrain() {
        List<ModeSettingBean.ModeSettingItemBean> itemBeans = new ArrayList<>();
        itemBeans.add(loopBean.getLoopCountItemBean());
        itemBeans.add(loopBean.getLoopTimeItemBean());

        List<String> itemMsgs = new ArrayList<>();
        itemMsgs.add(loopBean.getLoopCountItemBean().getDescWithItemTag(ModeSettingBean.ModeSettingItemTag.ModeSettingItemTagLoopCount));
        itemMsgs.add(loopBean.getLoopTimeItemBean().getDescWithItemTag(ModeSettingBean.ModeSettingItemTag.ModeSettingItemTagLoopTime));

        int index = this.loopBean.getLoopType();
        ModeSettingItemValuePopView popView = new ModeSettingItemValuePopView(this, itemBeans, itemMsgs, index, new ModeSettingItemValuePopView.OnSettingItemValuePopViewListner() {
            @Override
            public void onValueFinish(ModeSettingBean.ModeSettingItemBean itemBean, int index1) {
                loopBean.setLoopType(index1);
                startTrain();
            }

            @Override
            public void onValueError(String error) {
                showToast(error);
            }

            @Override
            public void onCancelBtnClick() {

            }
        });
        popView.show();
    }

    private void startTrain() {
        //运行的时间 次数
        boolean timeOrCount = loopBean.getLoopType() == 1;

        //循环次数
        int loopCount = timeOrCount ? 0 : loopBean.getLoopCountItemBean().getCurrentValue();
        //发球个数
        int count = loopCount;

        //单位分钟
        int loopMinute = timeOrCount ? loopBean.getLoopTimeItemBean().getCurrentValue() : 0;
        //转化为秒
        int time = loopMinute * 60;

        char[] data = DFS5ProtocolMaker.start(0, settingBean.getSteps());
        Intent intent = S5ModeBallActivity.makeIntent(this, settingBean.getName(), timeOrCount, time, count, data);
        startActivity(intent);
    }

    private void showItemValuePopView(ModeSettingBean.ModeSettingStepBean stepBean, ModeSettingBean.ModeSettingItemBean itemBean, ModeSettingBean.ModeSettingItemTag itemTag) {
        if (itemTag == ModeSettingBean.ModeSettingItemTag.ModeSettingItemTagNoRotation
                || itemTag == ModeSettingBean.ModeSettingItemTag.ModeSettingItemTagUpRotation
                || itemTag == ModeSettingBean.ModeSettingItemTag.ModeSettingItemTagDownRotation) {
            List<ModeSettingBean.ModeSettingItemBean> itemBeans = new ArrayList<>();
            itemBeans.add(stepBean.getUpRotationItemBean());
            itemBeans.add(stepBean.getNoRotationItemBean());
            itemBeans.add(stepBean.getDownRotationItemBean());

            List<String> itemMsgs = new ArrayList<>();
            itemMsgs.add(stepBean.getUpRotationItemBean().getDescWithItemTag(ModeSettingBean.ModeSettingItemTag.ModeSettingItemTagUpRotation));
            itemMsgs.add(stepBean.getNoRotationItemBean().getDescWithItemTag(ModeSettingBean.ModeSettingItemTag.ModeSettingItemTagNoRotation));
            itemMsgs.add(stepBean.getDownRotationItemBean().getDescWithItemTag(ModeSettingBean.ModeSettingItemTag.ModeSettingItemTagDownRotation));

            int index = 0;
            if (itemTag == ModeSettingBean.ModeSettingItemTag.ModeSettingItemTagNoRotation) {
                index = 1;
            } else if (itemTag == ModeSettingBean.ModeSettingItemTag.ModeSettingItemTagDownRotation) {
                index = 2;
            }

            ModeSettingItemValuePopView popView = new ModeSettingItemValuePopView(this, itemBeans, itemMsgs, index, new ModeSettingItemValuePopView.OnSettingItemValuePopViewListner() {
                @Override
                public void onValueFinish(ModeSettingBean.ModeSettingItemBean itemBean, int index) {
                    //0.不旋  1上旋  2下旋
                    int rotationType = 1;
                    if (index == 0) {
                        rotationType = 1;
                    } else if (index == 1) {
                        rotationType = 0;
                    } else if (index == 2) {
                        rotationType = 2;
                    }
                    stepBean.setRotationType(rotationType);
                    reloadData();
                }

                @Override
                public void onValueError(String error) {
                    showToast(error);
                }

                @Override
                public void onCancelBtnClick() {

                }
            });
            popView.show();
        } else {
            String itemMsg = itemBean.getDescWithItemTag(itemTag);
            ModeSettingItemValuePopView popView = new ModeSettingItemValuePopView(this, itemBean, itemMsg, new ModeSettingItemValuePopView.OnSettingItemValuePopViewListner() {
                @Override
                public void onValueFinish(ModeSettingBean.ModeSettingItemBean itemBean, int index) {
                    reloadData();
                }

                @Override
                public void onValueError(String error) {
                    showToast(error);
                }

                @Override
                public void onCancelBtnClick() {

                }
            });
            popView.show();
        }
    }

    private void showTextFiledAlert(String name) {
        CustomNameDialog dialog = new CustomNameDialog(this, new CustomNameDialog.OnDialogListner() {
            @Override
            public void onComfirmBtnClick(String text) {
                willSaveModeSettingModel(text);
            }

            @Override
            public void onCancelBtnClick() {
//                hideKeyboard();
            }
        });
        dialog.setTitle(getString(R.string.name_custom_mode));
        dialog.setName(name);
        dialog.show();
    }

    private void showDuplicationNameAlert(String name, int dataId) {
        String title = getString(R.string.name_duplication);
        CommonDialog dialog = new CommonDialog(this, title, null, new CommonDialog.OnCloseListener() {
            @Override
            public void onClick(Dialog dialog, boolean confirm) {
                if (confirm) {
                    showTextFiledAlert(name);
                } else {
                    saveModeSetting(name, dataId);
                }
            }
        });
        dialog.setNegativeButton(getString(R.string.replace));
        dialog.setNegativeButtonColor(getColor(R.color.blue));
        dialog.setPositiveButton(getString(R.string.rename));
        dialog.setPositiveButtonColor(getColor(R.color.red));
        dialog.show();
    }

    //准备保存自定义模式 保存之前判断一下是否重名
    private void willSaveModeSettingModel(String name) {
        if (name == null || name.isEmpty()) {
            showToast(getString(R.string.empty_name));
            return;
        }

        //	1.超8  2.超6  3.超5 4.超3
        int deviceType = AppCacheUtil.getInstance().getS3Ors5Type();
        DataBaseApi.queryCustomModelList(deviceType, null, new DataBaseApi.OnQueryCustomModelListListner() {
            @Override
            public void onCallback(boolean suc, List<ModeSettingBean> list) {
                if (suc) {
                    if (list != null) {
                        for (ModeSettingBean bind : list) {
                            if (name.equals(bind.getName())) {
                                //重名了
                                showDuplicationNameAlert(name, bind.getTid());
                                return;
                            }
                        }
                    }
                    saveModeSetting(name, 0);
                } else {
                    showToast(getString(R.string.fail_save));
                }
            }
        });
    }

    private void saveModeSetting(String name, int dataId) {
        if (name == null || name.isEmpty()) {
            showToast(getString(R.string.empty_name));
            return;
        }

        settingBean.setName(name);

        ModeSettingBean bean = new ModeSettingBean();
        bean.setName(name);
        bean.setProtocolType(ModeConstant.ProtocolTypeS5);
        bean.setDifficulty(99);
        bean.setTid(dataId);
        bean.setScript(settingBean.makeScript());

        //	1.超8  2.超6  3.超5 4.超3
        int deviceType = AppCacheUtil.getInstance().getS3Ors5Type();
        DataBaseApi.saveCustomModelInfo(deviceType, bean, new DataBaseApi.OnDatabaseCommonListner() {
            @Override
            public void onCallback(boolean suc) {
                if (suc) {
                    showToast(getString(R.string.success_save));
                    //发一个通知 到 模式列表页面 去刷新数据
                    EventBus.getDefault().post(new MessageEvent(MessageEvent.CUSTOM_MODE_CHANGED, null));
                } else {
                    showToast(getString(R.string.fail_save));
                }
            }
        });
    }
    //回收键盘
    private void hideKeyboard() {
        //回收键盘
        InputMethodManager imManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imManager != null && getCurrentFocus() != null) {
            imManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        }
    }
}
